@tool
class_name Unit
extends Node2D

#region Signals
signal quick_sell_pressed
#endregion

#region Exported parameters
@export var stats: UnitStats : set = _set_stats
#endregion

#region Internal parameters
@onready var skin: Sprite2D = %Skin

@onready var health_bar: ProgressBar = $UI/HealthBar
@onready var mana_bar: ProgressBar = $UI/ManaBar

@onready var drag_area: Area2D = %DragArea
@onready var drag_and_drop: DragAndDrop = %DragAndDrop
@onready var velocity_based_rotation: VelocityBasedRotation = %VelocityBasedRotation
@onready var outline_highlighter: OutlineHighlighter = %OutlineHighlighter

var is_hovered := false
#endregion


func _ready() -> void:
	if not Engine.is_editor_hint():
		drag_and_drop.drag_started.connect(_on_drag_started)
		drag_and_drop.drag_canceled.connect(_on_drag_canceled)
		drag_and_drop.dropped.connect(_on_dropped)
		drag_area.mouse_entered.connect(_on_mouse_entered)
		drag_area.mouse_exited.connect(_on_mouse_exited)


func _input(event: InputEvent) -> void:
	if is_hovered and event.is_action_pressed("quick_sell"):
		quick_sell_pressed.emit()


func _set_stats(value: UnitStats) -> void:
	stats = value
	
	if value == null:
		return
	
	if not is_node_ready():
		await ready
	
	skin.region_rect.position = Vector2(stats.skin_coordinates) * Arena.CELL_SIZE


func _on_drag_started() -> void:
	velocity_based_rotation.enabled = true


func _on_drag_canceled(start_local_position: Vector2) -> void:
	velocity_based_rotation.enabled = false
	global_position = start_local_position


func _on_dropped(_start_local_position: Vector2) -> void:
	velocity_based_rotation.enabled = false


func _on_mouse_entered() -> void:
	if drag_and_drop.dragging:
		return
	
	is_hovered = true
	outline_highlighter.highlight()
	z_index = 1


func _on_mouse_exited() -> void:
	if drag_and_drop.dragging:
		return
	
	is_hovered = false
	outline_highlighter.clear_highlight()
	z_index = 0
